<?php
namespace app\admin\controller;

use app\common\controller\Base;
use app\admin\library\Auth;
use think\facade\Url;

/*
* 后台控制器基类
*/
class BaseAdmin extends Base
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = [];  //无需鉴权的方法，但需要登录
	protected $auth = null;
	
	protected $admin = [];  //当前登录的管理员信息
	protected $adminMenuList = [];  //当前登录的管理员功能菜单

    //初始化
    public function initialize()
    {
		parent::initialize();
		//登录授权
		$this->auth = Auth::instance();
		//设置当前配置参数
		$this->auth->setAuthWebConfig($this->site);
		//用户登录信息
		$this->admin = $this->auth->getAdminInfo();
		//检测是否需要验证登录
		if(!$this->auth->match($this->noNeedLogin))
		{
			//检测是否登录
			if (!$this->admin)
			{
				$currAction = strtolower($this->request->action());
				if($currAction != 'logout' && $currAction != 'login')
				{
					$backUrl = $this->request->url(true);
					$loginUrl = Url::build('admin/index/login') . '?backurl=' . urlencode($backUrl);
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '登录超时，请退出重新登录。']));
					}else{
						return $this->redirect($loginUrl, '', 302);
					}
				}else{
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '登录超时，请退出重新登录。'],JSON_UNESCAPED_UNICODE));
					}else{
						return $this->redirect(Url::build('admin/index/login'), '', 302);
					}
				}
			}else{ //用户已登录
				//当前登录的管理员功能菜单
				$this->adminMenuList = $this->auth->getAdminMenu($this->admin);
			}
			//权限验证
			if(!$this->auth->match($this->noNeedRight))
			{
				if(!$this->auth->ruleCheck($this->currRouteUrl,$this->admin))
				{
					if($this->request->isAjax())
					{
						die(json_encode(['err' => '1', 'msg' => '对不起，操作未授权！'],JSON_UNESCAPED_UNICODE));
					}else{
						$turnPage = !$this->admin['index_page'] ? Url::build('admin/index/logout') : Url::build($this->admin['index_page']);
						return $this->error('对不起，操作未授权！', $turnPage);
					}
				}
			}
		}
		
		if(!$this->request->isAjax())
		{
			$this->assign([
				'curr_route' => $this->currRouteUrl, //当前路由
				'admin' => $this->admin, //当前登录的管理员信息
				'menu_list' => $this->adminMenuList, //当前登录的管理员功能菜单
			]);	
		}
    }

}
